import { Pie } from '@ant-design/plots';
import React, { useEffect, useState } from 'react';

interface ColumLineChartProps {
  pieChartID: string;
  yearParam: string;
  PieChartData: ColumLineChartDataList;
}

type ColumLineChartDataListItem = {
  type: string;
  value: number;
  name: string;
  action: string;
  obj: string;
};

type ColumLineChartDataList = ColumLineChartDataListItem[][];

const PieChart: React.FC<ColumLineChartProps> = ({
  pieChartID,
  yearParam,
  PieChartData,
}) => {
  let [data1, setData1] = useState(PieChartData[0]);

  //注意！！！，此处将状态更新的逻辑放在useEffect钩子中，以确保它只在yearParam发生变化时执行一次
  // 否则可能会在函数组件中的渲染过程中发生无限循环导致出错
  useEffect(() => {
    if (yearParam === '2023') {
      setData1(PieChartData[0]);
    } else if (yearParam === '2022') {
      setData1(PieChartData[1]);
    } else if (yearParam === '2021') {
      setData1(PieChartData[2]);
    }
  }, [yearParam]);

  const config = {
    data: data1,
    autoFit: 'true',
    angleField: 'value',
    colorField: 'type',
    innerRadius: 0.6,
    label: {
      text: 'value',
      style: {
        fontWeight: 'bold',
      },
    },
    legend: {
      color: {
        itemLabelFontSize: 12,
        itemLabelFill: '#fff',
        itemMarkerFillOpacity: 1,
        itemMarkerStrokeOpacity: 1,
      },
      size: {},
    },
    annotations: [
      {
        type: 'text',
        style: {
          text: '消费\n意向占比',
          fill: '#fff',
          x: '50%',
          y: '50%',
          textAlign: 'center',
          fontSize: 20,
          fontStyle: 'bold',
        },
      },
    ],
    tooltip: {
      title: false,
      items: [
        (d: any) => {
          return { name: d.type, value: `${d.value}%` };
        },
      ],
    },
  };
  return <Pie id={pieChartID} {...config} />;
};

export default PieChart;
